package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

// 返回数据的Controller
@Tag(name = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public AppResult register(@Param("用户名") @RequestParam("username") @NonNull String username,
                              @Param("密码") @RequestParam("password") @NonNull String password,
                              @Param("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @Param("重复密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

//        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(nickname) || StringUtils.isEmpty(passwordRepeat)){
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }

        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setNickname(nickname);

        String salt = UUIDUtil.uuid_32();
        String encryptPassword = MD5Util.md5Salt(password, salt);

        user.setPassword(encryptPassword);
        user.setSalt(salt);

        userService.createNormalUser(user);

        return AppResult.success();
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                            @Param("用户名") @RequestParam("username") String username,
                            @Param("密码") @RequestParam("password") String password) {
        // 1.调用service，返回user对象
        User user = userService.login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        // 2.登录成功把user对象存入session
        HttpSession session = request.getSession();
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 3.返回结果
        return AppResult.success();
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @Param("用户id") @RequestParam(value = "id",required = false)Long id){
        User user = null;
        if (id == null) {
            // 从session中获取用户信息
            HttpSession session = request.getSession(false);    // 没有session不创建
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            user = userService.selectById(id);
        }
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @Operation(summary = "用户登出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if (session != null) {
            log.info("用户登出");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @Operation(summary = "修改用户信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyUserInfo(HttpServletRequest request,
                                    @Param("用户名") @RequestParam(value = "username",required = false) String username,
                                    @Param("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                    @Param("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                    @Param("邮箱") @RequestParam(value = "email",required = false) String email,
                                    @Param("手机号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                    @Param("个人简介") @RequestParam(value = "remark",required = false) String remark
                                    ){
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && gender == null && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark)) {
            return AppResult.failed("请输入修改内容");
        }

        // httpSession获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 封装对象
        User updataUser = new User();
        updataUser.setId(user.getId());
        updataUser.setUsername(username);
        updataUser.setNickname(nickname);
        updataUser.setGender(gender);
        updataUser.setEmail(email);
        updataUser.setPhoneNum(phoneNum);
        updataUser.setRemark(remark);
        userService.modifyInfo(updataUser);
        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success(user);
    }

    @Operation(summary = "修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @Param("旧密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @Param("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @Param("确认密码") @RequestParam("passwordRepeat") @NonNull String PasswordRepeat){
        // 校验新密码和确认密码是否一致
        if (!newPassword.equals(PasswordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验旧密码是否正确
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 让session失效
        session.invalidate();
        return AppResult.success();
    }
}
